import _config from 'config';
import Toast from '../dist/toast/toast';
import _apiMap from 'api.js';
import md5 from 'md5.js';
const Util = function () {
  const self = this;
  self.NET_SUCCESS = 'ok';
  self.NET_MSG_KEY = 'msg';
  self.debug_key = _config.debug_key;
  self.version = _config.version;
  self.softid = _config.softid;
  self.token = false;
  self.api = _apiMap;
  self.debug = _config.debug;
  self.debugTime = 0;
  self.cache_fix = _config.cache_fix;
  self.baseUrl = _config.baseUrl;
  self.pageUrl = _config.pageUrl;
  self.javaUrl = _config.javaUrl;
  self.javaBiUrl = _config.javaBiUrl;
  self.bugToken = _config.bugToken;
  self.BdKey = 'Hz83kloQbnQHrXSVhaOG2DcqL6GKA2b1';
  self.BdJSKey = 'AtTsVqocV3qsMcHcwTEEhvhCDsHC06gb';
  self.log = function () {
    if (self.debug === true) {
      try {
        console.log.apply(console, arguments);
      } catch (e) {}
    }
  };
  self.HashMap = function () {
    let size = 0;
    let entry = {};
    this.put = function (key, value) {
      if (!this.containsKey(key)) {
        size++;
      }
      entry[key] = value;
    };
    this.get = function (key) {
      return this.containsKey(key) ? entry[key] : null;
    };
    this.remove = function (key) {
      if (this.containsKey(key) && (delete entry[key])) {
        size--;
      }
    };
    this.containsKey = function (key) {
      return (key in entry);
    };
    this.getKey = function () {
      let data = [];
      for (let prop in entry) {
        if (entry.hasOwnProperty(prop)) {
          data.push(prop);
        }
      }
      return data;
    };
    this.getData = function () {
      let data = [];
      for (let prop in entry) {
        if (entry.hasOwnProperty(prop)) {
          data.push(entry[prop]);
        }
      }
      return data;
    };
    this.containsValue = function (value) {
      for (let prop in entry) {
        if (entry.hasOwnProperty(prop)) {
          if (entry[prop] === value) {
            return true;
          }
        }
      }
      return false;
    };
    this.size = function () {
      return size;
    };
    this.clear = function () {
      size = 0;
      entry = {};
    };
  };
  self.getRandom = function (max, min) {
    min = arguments[1] || 0;
    return Math.floor(Math.random() * (max - min + 1) + min);
  };
  /**
   * 设置请求令牌
   * @param token
   */
  self.setToken = function (token) {
    self.token = token;
  };
  /**
   * 设置请求令牌
   * @param time
   */
  self.setDebugTime = function (time) {
    self.debug = true;
    self.debugTime = time;
  };
  /**
   * 设置请求域名
   * @param host
   */
  self.setApiHost = function (host) {
    if (!host || host.length < 10) {
      host = _config.baseUrl;
    }
    self.baseUrl = host;
  };
  /**
   * 弹出信息提示
   * 自带的太渣了.
   * @param title
   * @param d
   */
  self.msg = function (title, d) {
    let duration = d || 2000;
    Toast({
      type: 'text',
      position: 'bottom',
      message: title,
      zIndex: 2000,
      duration: duration,
    });
  };
  self.loading = function (title) {
    title = title || '加载中...';
    Toast.loading({
      mask: false,
      duration: 2500,
      message: title
    });
  };
  self.closeLoading = function () {
    Toast.clear();
  };
  /**
   * 写入本地缓存
   */
  self.cache_put = function (key, value, time) {
    wx.setStorageSync(key, value);
    let seconds = parseInt(time);
    if (seconds > 0) {
      let timestamp = Date.parse(new Date());
      timestamp = timestamp / 1000 + seconds;
      wx.setStorageSync(key + self.cache_fix, timestamp + "")
    } else {
      wx.removeStorageSync(key + self.cache_fix)
    }
  };
  /**
   * 获取本地缓存
   */
  self.cache_get = function (key, default_value) {
    let deadtime = parseInt(wx.getStorageSync(key + self.cache_fix));
    if (deadtime) {
      if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
        if (default_value) {
          return default_value;
        } else {
          return;
        }
      }
    }
    let res = wx.getStorageSync(key);
    if (res) {
      return res;
    } else {
      return default_value;
    }
  };
  /**
   * 移除本地缓存
   */
  self.cache_remove = function (key) {
    wx.removeStorageSync(key);
    wx.removeStorageSync(key + self.cache_fix);
  };
  /**
   * 清除本地缓存
   */
  self.cache_clear = function () {
    wx.clearStorageSync();
  };
  /**
   * 网络请求封装
   * @param param
   * @returns {boolean}
   */
  self.request = function (param) {
    let header = {};
    let log = false;
    let app = getApp();
    let startTime = 0;
    param.type = param.type || 'POST';
    param.dataType = param.dataType || 'json';
    param.data = param.data || {};
    param.handle = param.handle || false;
    param.actionName = param.actionName || false;
    param.loading = param.loading || true;
    param.autoAuth = param.autoAuth || true;
    param.setToken = param.setToken || 1;
    param.dev = param.dev || true;
    param.timeout = param.timeout || 10000;
    if (typeof (param.url) === 'undefined' || param.url.length === 0) {
      param.callback && param.callback({});
      return true;
    }
    /**
     * 成功回调处理
     * @param result
     * @param _param
     */
    function success(result, _param) {
      let data;
      if (_param.loading === true) {
        self.closeLoading();
      }
      if (result.hasOwnProperty('res') && typeof (result.res) === 'object') {
        data = result.res;
        //主动更新Token
        if (data && _param.setToken === 1 && data.hasOwnProperty('token')) {
          self.setToken(data.token);
          wx.setStorageSync('token', data.token);
          wx.removeStorageSync('t_token');
        }
      }
      if (_param.handle) {
        _param.callback && _param.callback(result);
      } else {
        if (result.status === self.NET_SUCCESS) {
          _param.callback && _param.callback(result);
        } else {
          console.log('接口报错：', _param.url, _param.data, result);
          if (result.hasOwnProperty('code') && result['code'] === 2007) {
            app.globalData.userInfo = null;
            app.globalData.encryptKey = null;
            self.cache_remove('encryptKey');
            self.cache_remove('token');
            self.cache_remove('t_token');
            self.cache_remove('_uInfo');
            self.setToken('');
            try {
              if (_param.autoAuth === true) {
                self.msg('错误：' + (result[self.NET_MSG_KEY] ? result[self.NET_MSG_KEY] : result['detail']));
                let page = getCurrentPages();
                page[page.length - 1].setData({
                  initUser: false,
                  openLogin: true
                });
              }
            } catch (e) {
              self.log(e);
            }
          } else {
            self.msg('错误：' + (result[self.NET_MSG_KEY] ? result[self.NET_MSG_KEY] : result['detail']));
          }
          wx.getLogManager({
            level: 1
          }).warn(_param.url, _param.data, result);
          _param.error && _param.error(result);
        }
      }
    }
    //自动添加令牌和版本号
    if (self.token) {
      header['token'] = self.token;
    }
    if (self.version) {
      header['version'] = self.version;
    }
    if (!param.data.hasOwnProperty('softid')) {
      param.data.softid = self.softid;
      param.data.soft_id = self.softid;
    }
    if (param.loading === true) {
      try {
        self.loading();
      } catch (e) {}
    }
    if (param.url.substring(0, 4) !== 'http') {
      if (param.hasOwnProperty('isJava')) {
        param.url = self.javaUrl + param.url;
      } else {
        param.url = self.baseUrl + param.url;
      }
    }
    /**
     * 处理多//问题
     */
    param.url = param.url.replace('.com//', '.com/');
    if (self.debugTime > new Date().getTime()) {
      startTime = new Date().getTime();
      log = true;
    }
    wx.request({
      url: param.url,
      data: param.data,
      method: param.type,
      header: header,
      dataType: param.dataType,
      success: function (response) {
        if (log === true) {
          self.log('地址:', param.url, '参数:', param, '响应:', response, '耗时：', (new Date().getTime() - startTime));
        }
        if (typeof (response.data) !== 'object') {
          if (param.handle) {
            param.error && param.error(response.data);
          } else {
            self.msg('服务器异常-502!');
            wx.getLogManager({
              level: 1
            }).warn(param.url, param.data, response);
            param.error && param.error({});
          }
        } else {
          success(response.data, param);
        }
      },
      fail: function (result) {
        if (log === true) {
          self.log('错误信息:', result);
        }
        if (param.loading === true) {
          self.closeLoading();
        }
        wx.getLogManager({
          level: 1
        }).warn(param.url, param.data, result);
        if (param.handle) {
          param.error && param.error(result);
        } else {
          // self.msg('网络异常,请求失败!');
          param.error && param.error({});
        }
      },
      complete: function (res) {
        self.trackPut({
          actionType: 2,
          actionName: param.actionName ? param.actionName : param.url.replace(param.isJava ? self.javaUrl : self.baseUrl, ''),
          actionPara: param.data,
        });
      }
    });
  };
  /**
   * 快速跳转页面
   * @param event
   * @param callback
   * @param redirectTo
   */
  self.toPage = function (event, callback, redirectTo) {
    let page = '';
    let type = 'page';
    let data = {};
    if (typeof event === 'string') {
      page = event;
    } else {
      data = event.currentTarget.dataset;
      if (data.hasOwnProperty('route') && data['route'] === 'false') {
        if (data.hasOwnProperty('text') && data['text'] !== '') {
          self.msg(data['text']);
        }
        return true;
      }
      if (data.page) {
        page = data.page;
      }
      if (data.hasOwnProperty('title')) {
        data.title = encodeURIComponent(data.title);
      }
      if (data.type) {
        type = data.type;
      }
      if (type !== 'url' && data.title) {
        if (page.indexOf('?') === -1) {
          page += '?title=' + data.title;
        } else {
          if (page.indexOf('#wechat_redirect') === -1) {
            page += '&title=' + data.title;
          } else {
            page = page.replace('#wechat_redirect', '&title=' + data.title + '#wechat_redirect');
          }
        }
      }
    }
    if (page.substring(0, 4) === 'http') {
      type = 'url';
    }
    if (page.length > 0) {
      switch (type) {
        case 'url':
          if (redirectTo) {
            wx.redirectTo({
              url: '/pages/index/web/index?url=' + encodeURIComponent(page) + (data.title ? '&title=' + data.title : ''),
              success: function (e) {
                callback && callback(this, e);
              }
            });
          } else {
            wx.navigateTo({
              url: '/pages/index/web/index?url=' + encodeURIComponent(page) + (data.title ? '&title=' + data.title : ''),
              success: function (e) {
                callback && callback(this, e);
              }
            });
          }
          break;
        case 'tabar':
          let options = {};
          let strs;
          if (page.indexOf('?') !== -1) {
            let str = page.split('?')[1];
            page = page.split('?')[0];
            strs = str.split("&");
            for (let i = 0; i < strs.length; i++) {
              options[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
            }
          }
          wx.switchTab({
            url: page,
            success: function (e) {
              if (JSON.stringify(options) !== '{}') {
                let pages = getCurrentPages();
                let rpage = page.replace('/pages/', 'pages/');
                let flag = false;
                for (let i = 0; i < pages.length; i++) {
                  if (rpage === pages[i]['route']) {
                    pages[i].onLoad(options);
                    flag = true;
                    break;
                  }
                }
                if (flag === false) {
                  setTimeout(function () {
                    let pages = getCurrentPages();
                    for (let i = 0; i < pages.length; i++) {
                      if (rpage === pages[i]['route']) {
                        pages[i].onLoad(options);
                        break;
                      }
                    }
                  }, 1000);
                }
              }
              callback && callback(this, e);
            }
          });
          break;
        default:
          if (redirectTo) {
            wx.redirectTo({
              url: page,
              success: function (e) {
                callback && callback(this, e);
              },
              fail(res) {
                console.log(res);
                if (res.errMsg.indexOf('bar') > -1) {
                  self.toPage({
                    currentTarget: {
                      dataset: {
                        page: page,
                        type: 'tabar'
                      }
                    }
                  })
                }
              }
            });
          } else {
            wx.navigateTo({
              url: page,
              success: function (e) {
                callback && callback(this, e);
              },
              fail(res) {
                console.log(res);
                if (res.errMsg.indexOf('bar') > -1) {
                  self.toPage({
                    currentTarget: {
                      dataset: {
                        page: page,
                        type: 'tabar'
                      }
                    }
                  })
                }
              }
            });
          }
          break;
      }
    }
  };
  /**
   * 用户来源处理
   * @param param
   */
  self.setChannel = function (param) {
    let app = getApp();
    let local = {};
    let channel = {
      fstr: '',
      ekey: '',
      uid: 0,
    };
    let json_str;
    local = self.getChannel();
    if (!local.hasOwnProperty('fstr')) {
      local['fstr'] = '';
    }
    if (!local.hasOwnProperty('ekey')) {
      local['ekey'] = '';
    }
    if (!local.hasOwnProperty('uid')) {
      local['uid'] = 0;
    }
    channel['fstr'] = local.fstr;
    channel['ekey'] = local.ekey;
    channel['uid'] = local.uid;
    if (param.hasOwnProperty('ekey')) {
      channel.ekey = param.ekey;
    }
    if (param.hasOwnProperty('fstr')) {
      channel.fstr = param.fstr;
    }
    if (param.hasOwnProperty('uid')) {
      channel.uid = isNaN(parseInt(param.uid)) ? 0 : parseInt(param.uid);
    }
    json_str = JSON.stringify(channel);
    if (JSON.stringify(local) !== json_str && json_str !== '{"ekey":"","fstr":"","uid":0}') {
      app.globalData.channel = channel;
      self.cache_put('channel_2', channel);
    }
  };
  /**
   * 获取来源
   * @returns {string}
   */
  self.getChannel = function (k) {
    let app = getApp();
    let channel = {};
    let key = k || 'all';
    if (app.globalData.hasOwnProperty('channel')) {
      channel = app.globalData.channel;
    }
    if (!channel || JSON.stringify(channel) === '{"ekey":"","fstr":""}') {
      channel = self.cache_get('channel_2', channel);
    }
    if (key === 'all') {
      return channel;
    }
    if (key === 'fstr') {
      return channel.hasOwnProperty('fstr') ? channel['fstr'] : '';
    }
    if (key === 'ekey') {
      return channel.hasOwnProperty('ekey') ? channel['ekey'] : '';
    }
    if (key === 'uid') {
      return channel.hasOwnProperty('uid') ? channel['uid'] : 0;
    }
    return '';
  };
  self.formatTime = function (fmt, times) {
    let date = new Date(times * 1000);
    let o = {
      "M+": date.getMonth() + 1, //月份
      "d+": date.getDate(), //日
      "h+": date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, //小时
      "H+": date.getHours(), //小时
      "m+": date.getMinutes(), //分
      "s+": date.getSeconds(), //秒
      "q+": Math.floor((date.getMonth() + 3) / 3), //季度
      'T+': date.getHours() < 12 ? '上午' : '下午',
      "S": date.getMilliseconds() //毫秒
    };
    let week = {
      "0": "\u65e5",
      "1": "\u4e00",
      "2": "\u4e8c",
      "3": "\u4e09",
      "4": "\u56db",
      "5": "\u4e94",
      "6": "\u516d"
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[date.getDay() + ""]);
    }
    for (let k in o) {
      if (new RegExp("(" + k + ")").test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      }
    }
    return fmt;
  };
  /**
   * 格式化金额到元并设置千分位
   */
  self.formatMoney = function (money, t) {
    let type = t || 1;
    if (money === 0) {
      return 0;
    } else {
      money = money * 0.01;
      money = parseFloat(money.toFixed(2));
      if (t === 2) {
        return money;
      }
      return money.toLocaleString();
    }
  };
  self.fixInt = function (val) {
    val = parseInt(val);
    return isNaN(val) ? 0 : val;
  };
  self.fixFloat = function (val) {
    val = parseFloat(val);
    return isNaN(val) ? 0 : val;
  };
  /**
   * 获取店铺Logo文字
   * @param name
   * @returns {string}
   */
  self.getMallLogoText = function (name) {
    let first = '';
    if (name.length > 0) {
      first = name.substring(0, 1);
    }
    return first;
  };
  /**
   * 维护一个本地临时图片文件列表
   */
  self.getImageCache = function (url, callback, fail) {
    let c_key = 'temp_images';
    //生成短KEY
    let u_key = url.replace('https://', '');
    let c_info = self.cache_get(c_key, false);
    if (c_info === false) {
      c_info = {};
    }
    let getImageInfo = function (url, callback) {
      wx.getImageInfo({
        src: url,
        success: function (res) {
          callback && callback(res);
        },
        fail: function () {
          fail && fail(2);
        }
      });
    };
    if (c_info.hasOwnProperty(u_key)) {
      //本地有缓存数据
      getImageInfo(c_info[u_key], callback);
    } else {
      //本地无缓存文件
      self.downloadFile(url, function (temp_url) {
        c_info[u_key] = temp_url;
        self.cache_put(c_key, c_info);
        getImageInfo(temp_url, callback);
      }, function () {
        fail && fail(1);
      });
    }
  };
  /**
   * 下载文件到本地
   * @param url
   * @param callback
   * @param fail
   */
  self.downloadFile = function (url, callback, fail) {
    wx.downloadFile({
      url: url,
      success: function (res) {
        callback && callback(res.tempFilePath);
      },
      fail: function () {
        fail && fail(false);
      }
    });
  };
  /**
   * 格式化地区到字符串中
   * @param item
   * @param split
   * @param t
   * @returns {string}
   */
  self.formatAreaToString = function (item, split, t) {
    let spString = split || '';
    let type = t || 1;
    let arrInfo = [];
    let arrString = '';
    if (item.hasOwnProperty('province') && item['province'].length > 0) {
      arrInfo.push(item.province);
    }
    if (item.hasOwnProperty('city') && item['city'].length > 0) {
      arrInfo.push(item.city);
    }
    if (arrInfo.length === 0 && item.hasOwnProperty('controy') && item['controy'].length > 0) {
      arrInfo.push(item.controy);
    }
    if (arrInfo.length > 0) {
      arrString = arrInfo.join(spString);
    }
    if (type === 1 && item.hasOwnProperty('address') && item['address'].length > 0) {
      arrString = item['address'];
    }
    if (arrString !== spString) {
      return arrString;
    } else {
      return '';
    }
  };
  /**
   * 设置视频页tabBar
   * @param t
   */
  self.setVideoTabBar = function (t) {};
  /**
   * 获取设备UUID
   * @returns {*|string|undefined}
   */
  self.getUUID = function () {
    let local = self.cache_get('vkey_token', false);
    let sysInfo;
    let tString = [];
    if (!local) {
      sysInfo = wx.getSystemInfoSync();
      console.log('sysInfo', sysInfo);
      tString.push(sysInfo.brand);
      tString.push(sysInfo.model);
      tString.push(sysInfo.pixelRatio);
      tString.push(sysInfo.screenWidth);
      tString.push(sysInfo.screenHeight);
      tString.push(sysInfo.system);
      tString.push(sysInfo.SDKVersion);
      tString.push(self.getRandom(99999, 10000));
      local = md5(tString.join('_'));
      self.cache_put('vkey_token', local);
    }
    return local;
  };
  self.rpxToPx = function (val) {
    let sysInfo = wx.getSystemInfoSync();
    let width = sysInfo.windowWidth;
    let ratio = self.fixInt((width / 750) * 100);
    return self.fixInt(val * (ratio / 100));
  };
  /*
   * 将秒数格式化时间
   * @param {Number} seconds: 整数类型的秒数
   * @return {String} time: 格式化之后的时间
   */
  self.formatTimeText = function (seconds) {
    let min = Math.floor(seconds / 60),
      second = parseInt(seconds % 60),
      hour, newMin, time;
    if (min > 60) {
      hour = Math.floor(min / 60);
      newMin = min % 60;
    }

    if (newMin < 10) {
      newMin = '0' + newMin;
    }
    if (second < 10) {
      second = '0' + second;
    }
    if (min < 10) {
      min = '0' + min;
    }

    return time = hour ? (hour + '小时' + newMin + '分' + second + '秒') : (min + '分' + second + '秒');
  };

  self.trackPut = function (param) {
    let header = {};
    let data = {};
    let actPage = false;
    let pages = getCurrentPages();
    let app = getApp();
    let flag = true;
    let send = false;
    let sendD = [];
    let map = {
      'actionType': 'a',
      'actionName': 'an',
      'actionPara': 'ap',
      'firstVisit': 'f',
      'pageName': 'p',
      'pagePara': 'pa',
      'pageParent': 'pp',
      'storeId': 'st',
      'token': 'to',
    };
    if (param.hasOwnProperty('openBi') && param.openBi === true) {
      flag = true;
    }
    flag = false;
    if (!flag) {
      return false;
    }
    if (pages.length > 0) {
      actPage = pages[pages.length - 1];
      if (!param.hasOwnProperty('pageParent')) {
        if (pages.length > 1) {
          param['pageParent'] = pages[pages.length - 2]['route'];
        }
      }
    }
    if (!param.hasOwnProperty('pageName') && actPage) {
      param['pageName'] = actPage['route'];
    }
    if (!param.hasOwnProperty('firstVisit')) {
      param['firstVisit'] = 2;
    }
    if (!param.hasOwnProperty('pagePara') && actPage && actPage.hasOwnProperty('options')) {
      param['pagePara'] = actPage['options'];
    }
    if (param.actionPara && param.actionPara.hasOwnProperty('store_id')) {
      param['storeId'] = param['actionPara']['store_id'];
    } else {
      if (actPage && actPage.data.hasOwnProperty('store_id')) {
        param['storeId'] = actPage['data']['store_id'];
      }
    }
    if (self.token) {
      param['token'] = self.token;
    }
    for (let key in map) {
      param.hasOwnProperty(key) && (data[map[key]] = param[key]);
    }
    if (data.hasOwnProperty('ap')) {
      data['ap'] = JSON.stringify(data['ap']);
    }
    if (data.hasOwnProperty('pa')) {
      data['pa'] = JSON.stringify(data['pa']);
    }
    data['c'] = 3;
    data['s'] = 0;
    data['t'] = new Date().getTime();

    app.globalData.trackData.push(data);
    if (app.globalData.trackData.length >= 10) {
      send = true;
    }
    if (param.hasOwnProperty('flush')) {
      send = true;

    }
    if (send === false) {
      return false;
    }
    sendD = app.globalData.trackData;
    app.globalData.trackData = [];
    if (sendD.length <= 0) {
      return false;
    }
    setTimeout(function () {
      wx.request({
        url: self.javaBiUrl + 'track/put',
        data: {
          requestsList: sendD
        },
        method: 'POST',
        header: header,
        dataType: 'JSON',
        success: function (response) {},
        fail: function (result) {},
        complete: function (res) {
          console.log('track', res);
        }
      });
    }, 800);
  };
  self.getAdId = function (long) {
    let id = '';
    const AD_UNIT_ID = ['adunit-b5fbbe96f27d0e64', 'adunit-907a6b7199dc7f90']
    return AD_UNIT_ID[self.getRandom(AD_UNIT_ID.length - 1, 0)]
  };


  self.getDayADid = function (long) {
    let adid = 'adunit-752f434c54d8cb7a' //30s
    let adid2 = 'adunit-096f211c557c9d13' // 15s
    var timestamp = new Date().getTime();
    let dayNum = 0
    let time = self.formatTime('yyyyMMdd', timestamp / 1000) //今天日期
    let day = wx.getStorageSync('day') || time //缓存日期 没有则默认今天日期
    if (day === time) { //如果今天等于缓存
      dayNum = parseInt(wx.getStorageSync('adNum')) || 0
      wx.setStorageSync('adNum', dayNum + 1)
    } else {
      wx.setStorageSync('day', time)
      wx.setStorageSync('adNum', 1)
    }
    if (dayNum < 2) {
      return adid
    } else {
      return adid2
    }
  }


  self.isShowBannerAd = function () {
    var timestamp = new Date().getTime();
    let taday = self.formatTime('yyyyMMdd', timestamp / 1000) //今天日期
    let day = wx.getStorageSync('day') || '000' //缓存日期 没有则默认000
    wx.setStorageSync('day', taday)
    if (taday === day) {
      return false
    } else {
      return true
    }
  }


  self.UserUv = function (ekey) {
    if (!ekey) {
      return;
    }
    self.request({
      url: 's/lottery/ShareView',
      data: {
        ekey: ekey
      },
      handle: true,
      loading: 2,
      error: function (res) {},
      success: function (res) {}
    })
  };
  self.sprintf = function (str) {
    if (arguments.length === 1) return this;
    let param = arguments[1];
    if (typeof (param) === 'object') {
      for (let key in param) {
        str = str.replace(new RegExp("\\{" + key + "\\}", "g"), param[key]);
      }
    } else {
      for (let i = 1; i < arguments.length; i++) {
        str = str.replace(new RegExp("\\{" + i + "\\}", "g"), arguments[i]);
      }
    }
    return str;
  };
};
const _Util = new Util();
_Util.setToken(wx.getStorageSync('token') || false);
// _Util.setToken('60483_000000');
_Util.setDebugTime(wx.getStorageSync('debug') || 0);
_Util.setApiHost(wx.getStorageSync('api_host') || false);
// Virtual.init();
module.exports = _Util;
